package com.shangma.cn.components;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 开发者：辉哥
 * 特点： 辉哥很帅
 * 开发时间：2021/7/1 11:44
 * 文件说明：
 */

@Component
public class CacheService {

    public static final long defaultTime = 300;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public void setCache(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    public void setCache(String key, String value, long second) {
        stringRedisTemplate.opsForValue().set(key, value, second, TimeUnit.SECONDS);
    }

    public void setCacheWithDefaultTime(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value, defaultTime, TimeUnit.SECONDS);
    }

    public String getCache(String key) {
        if (hasKey(key)) {
            return stringRedisTemplate.opsForValue().get(key);
        }
        return "";
    }

    public boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    public void removeCache(String key) {
        stringRedisTemplate.delete(key);
    }


}
